package com.pureut.production.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.*;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.dto.storage.dto.WarehouseDto;
import com.pureut.production.domain.system.domain.SysDocument;
import com.pureut.production.domain.system.dto.SysDocumentCheckDto;
import com.pureut.production.domain.vo.DegreasOutputDetailVo;
import com.pureut.production.domain.vo.DegreasOutputVo;
import com.pureut.production.domain.vo.ScanInVo;
import com.pureut.production.domain.vo.WasteTubeVo;
import com.pureut.production.mapper.*;
import com.pureut.production.service.DegreasDocumentService;
import com.pureut.production.service.DegreasOutputDetailService;
import com.pureut.production.service.DegreasOutputService;
import com.pureut.system.api.*;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.MaterialNumberAndBatchNoVo;
import com.pureut.system.api.vo.QualityInspectionDocumentVo;
import com.pureut.system.api.vo.WipOtherAddVo;
import com.pureut.system.api.vo.WmsStockInfoVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 脱脂产出实现层
 */
@Service
public class DegreasOutputServiceImpl extends ServiceImpl<DegreasOutputMapper, DegreasOutput> implements DegreasOutputService {

    /**
     * 脱脂产出mapper
     */
    @Resource
    DegreasOutputMapper degreasOutputMapper;

    /**
     * 脱脂产出明细service
     */
    @Resource
    DegreasOutputDetailService degreasOutputDetailService;

    /**
     * 脱脂产出明细mapper
     */
    @Resource
    DegreasOutputDetailMapper degreasOutputDetailMapper;

    /**
     * 基础模块fegin
     */
    @Resource
    FeignService feignService;

    /**
     * 仓库模块fegin
     */
    @Resource
    StorageFegin storageFegin;

    /**
     * 品质fegin
     */
    @Resource
    QualityFeginService qualityFeginService;

    /**
     * 物料信息mapper
     */
    @Resource
    MaterialFinishedMapper materialFinishedMapper;

    /**
     * 排程fegin
     */
    @Resource
    SchedulingPlanFeignService schedulingPlanFeignService;

    /**
     * 车间建模mapper
     */
    @Resource
    SysShopModelingMapper sysShopModelingMapper;

    /**
     * 检验配置fegin
     */
    @Resource
    SystemDocumentFeignService systemDocumentFeignService;

    /**
     * 废料管理mapper
     */
    @Resource
    WasteTubeMapper wasteTubeMapper;

    /**
     * 脱脂制令单mapper
     */
    @Resource
    DegreasDocumentMapper degreasDocumentMapper;

    /**
     * 脱脂制令单mapper
     */
    @Resource
    DegreasDocumentService degreasDocumentService;

    /**
     * 脱脂产出列表
     *
     * @param degreasOutputVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<DegreasOutputDto> getList(DegreasOutputVo degreasOutputVo) {

        return degreasOutputMapper.getOutputList(degreasOutputVo);
    }

    /**
     * 脱脂产出新增
     *
     * @param degreasOutputVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDegreasOutput(DegreasOutputVo degreasOutputVo) {
        DegreasOutput degreasOutput = new DegreasOutput();
        degreasOutput.setDegreasOrderNumber(degreasOutputVo.getDegreasOrderNumber())
                .setProductStatus(2)
                .setMaterialCode(degreasOutputVo.getMaterialCode())
                .setPlanWeight(degreasOutputVo.getPlanWeight())
                .setLineCode(degreasOutputVo.getLineCode())
                .setCreateBy(SecurityUtils.getUsername())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId());
        return save(degreasOutput);
    }

    /**
     * 产出
     *
     * @param degreasOutputDetailVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean outPut(DegreasOutputDetailVo degreasOutputDetailVo) throws Exception {
        DegreasOutput degreasOutput = degreasOutputMapper.selectOne(new QueryWrapper<DegreasOutput>().lambda().eq(DegreasOutput::getDegreasOrderNumber, degreasOutputDetailVo.getDegreasOrderNumber()));

        //
        DegreasDocument degreasDocument = degreasDocumentMapper.selectOne(new QueryWrapper<DegreasDocument>().lambda().eq(DegreasDocument::getDegreasOrderNumber, degreasOutputDetailVo.getDegreasOrderNumber()));
        //获取缸号字典
        List<SysDictData> cylinderNumberArray = DictUtils.getDictCache("cylinder_number");
        Map<String, String> cylinderNumberMap = cylinderNumberArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取班次字典
        List<SysDictData> classInfoArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classInfoMap = classInfoArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取缸次字典
        List<SysDictData> cylinderOrderArray = DictUtils.getDictCache("cylinder_order");
        Map<String, String> cylinderOrderMap = cylinderOrderArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //只能对状态为“生产中”的制令单进行产出打印
        if (degreasOutput.getProductStatus() == 2) {
            //打印后，在主页面下表记录对应的物料信息，状态为“待入库”
            DegreasOutputDetail degreasOutputDetail = new DegreasOutputDetail();
            //获取跨天时间和班次
            AjaxResult ajaxResult = schedulingPlanFeignService.selectShiftLine(degreasOutput.getLineCode());
            if (ajaxResult == null) {
                throw new GlobalException("获取跨天时间和班次失败");
            }
            List<CalendarTeamDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), CalendarTeamDto.class);

            Date crossSkyTime = null;
            String classDifference = null;
            for (CalendarTeamDto entity : data) {

                Date nowTime = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(nowTime);
                Date time = calendar.getTime();
                //判断当前时间是否在开始时间和结束时间之内
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                String time2 = simpleDateFormat.format(time);
                String time3 = entity.getTeamStartTime();
                String time4 = entity.getTeamEndTime();
                if (time2.compareTo(time3) > 0 && time2.compareTo(time4) < 0) {
                    //获取班组
                    classDifference = entity.getTeamInfo();
                    //判断是否跨天,并判断当前时间小于开始时间
                    if (entity.getTeamTranssky() == 1 && time2.compareTo(time3) < 0) {
                        //如果跨天就取前一天
                        Date date = new Date();
                        //得到日历
                        Calendar calendar1 = Calendar.getInstance();
                        //把当前时间赋给日历
                        calendar1.setTime(date);
                        //设置为前一天
                        calendar1.add(Calendar.DAY_OF_MONTH, -1);
                        //得到前一天的时间
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sf.format(calendar1.getTime());
                        //得到前一天的时间
                        crossSkyTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
                    } else {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sf.format(new Date());
                        //得到前一天的时间
                        crossSkyTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
                    }
                }
            }
            if (crossSkyTime == null && classDifference == null) {
                throw new GlobalException("未进行工厂日历配置");
            }
            //包号
            int i = 1;
            String newNumber = cylinderNumberMap.get(degreasOutputDetailVo.getCylinderNumber()) + cylinderOrderMap.get(degreasOutputDetailVo.getCylinderOrder());
            List<DegreasOutputDetail> degreasOutputDetails = degreasOutputDetailMapper.selectList(new QueryWrapper<DegreasOutputDetail>().lambda().eq(DegreasOutputDetail::getDegreasOrderNumber, degreasOutput.getDegreasOrderNumber()).eq(DegreasOutputDetail::getCylinderNumber, newNumber).orderByDesc(DegreasOutputDetail::getOutputTime));

            if (degreasOutputDetails.size() > 0) {
                String cylinderNumber = degreasOutputDetails.get(0).getCylinderNumber();
                if (newNumber.equals(cylinderNumber)) {
                    i = degreasOutputDetails.get(0).getPackNumber() + 1;
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
            String format = simpleDateFormat.format(new Date());

            String batchNumber = format + classInfoMap.get(classDifference) + "-" + newNumber;
            String degreasOrderNumber = degreasOutput.getDegreasOrderNumber();
            AjaxResult documentByBatchNumber = qualityFeginService.getDocumentByBatchNumber(batchNumber, degreasOrderNumber);
            //获取该批次下的已完成的品质检验单数据
            QualityInspectionDocumentDto qualityInspectionDocumentDto = JSON.parseObject(JSON.toJSONString(documentByBatchNumber.get("data")), QualityInspectionDocumentDto.class);
            String dc = feignService.splitList("DC");

            String str1 = degreasOrderNumber.substring(0, degreasOrderNumber.indexOf("-"));
            String str2 = degreasOrderNumber.substring(str1.length() + 1);
            //如果没有获取到已完成的品质检验单
//            if (qualityInspectionDocumentDto.getInspectionSheetNo() == null) {
            degreasOutputDetail.setMaterialNumber("DC" + str2 + "-" + dc)
                    .setStatus(1)
//                    .setCheckStatus(1)
                    .setRemark(degreasOutputDetailVo.getRemark())
                    .setTemplateId(degreasDocument.getDegreasMark())
                    .setDegreasOrderNumber(degreasOutput.getDegreasOrderNumber())
                    .setMaterialCode(degreasOutputDetailVo.getMaterialCode())
                    .setCylinderNumber(cylinderNumberMap.get(degreasOutputDetailVo.getCylinderNumber()) + cylinderOrderMap.get(degreasOutputDetailVo.getCylinderOrder()))
                    .setPackNumber(i)
                    .setBatchNumber(batchNumber)
                    .setGrossWeight(degreasOutputDetailVo.getGrossWeight())
                    .setNetWeight(degreasOutputDetailVo.getNetWeight())
                    .setOutputTime(new Date())
                    .setShift(classDifference)
                    .setOperator(SecurityUtils.getUsername());
            if (qualityInspectionDocumentDto.getInspectionSheetNo() != null) {
                degreasOutputDetail.setCheckResult(Integer.parseInt(qualityInspectionDocumentDto.getInspectionResults()));
                if (Integer.parseInt(qualityInspectionDocumentDto.getStatus()) == 7) {
                    degreasOutputDetail.setCheckStatus(2);
                }
                degreasOutputDetail.setMaterialLevel(Integer.parseInt(qualityInspectionDocumentDto.getJudgmentGrade()));
            }
            degreasOutputDetailService.save(degreasOutputDetail);
//            } else {
//                degreasOutputDetail.setMaterialNumber("DC" + str2 + "-" + dc)
//                        .setStatus(1)
//                        .setCheckStatus(2)
//                        .setCheckResult(Integer.parseInt(qualityInspectionDocumentDto.getInspectionResults()))
//                        .setRemark(degreasOutputDetailVo.getRemark())
//                        .setTemplateId(degreasDocument.getDegreasMark())
//                        .setDegreasOrderNumber(degreasOutput.getDegreasOrderNumber())
//                        .setMaterialCode(degreasOutputDetailVo.getMaterialCode())
//                        .setCylinderNumber(cylinderNumberMap.get(degreasOutputDetailVo.getCylinderNumber()) + cylinderOrderMap.get(degreasOutputDetailVo.getCylinderOrder()))
//                        .setPackNumber(i)
//                        .setBatchNumber(batchNumber)
//                        .setGrossWeight(degreasOutputDetailVo.getGrossWeight())
//                        .setNetWeight(degreasOutputDetailVo.getNetWeight())
//                        .setOutputTime(new Date())
//                        .setShift(classDifference)
//                        .setOperator(SecurityUtils.getUsername());
//                if ("1".equals(qualityInspectionDocumentDto.getJudgmentGrade())) {
//                    //良品
//                    degreasOutputDetail.setMaterialLevel(1);
//                } else if ("3".equals(qualityInspectionDocumentDto.getJudgmentGrade())) {
//                    //返工
//                    degreasOutputDetail.setMaterialLevel(3);
//                } else {
//                    //报废
//                    degreasOutputDetail.setMaterialLevel(2);
//                }
            //如果该单据检验结果为合格
//                if ("1".equals(qualityInspectionDocumentDto.getInspectionResults())) {
//                    //将该明细净重作为良品产出重量
//                    BigDecimal bigDecimalOld = new BigDecimal(String.valueOf(degreasOutputDetailVo.getNetWeight()));
//                    BigDecimal bigDecimalGood = new BigDecimal(String.valueOf(degreasOutput.getGoodOutputWeight()));
//                    String s = bigDecimalOld.add(bigDecimalGood).toString();
//                    degreasOutput.setGoodOutputWeight(Double.parseDouble(s));
//                    degreasDocument.setGoodOutputWeight(Double.parseDouble(s));
//                } else {
//                    //将该明细净重作为不良品产出重量
//                    BigDecimal bigDecimalOld = new BigDecimal(String.valueOf(degreasOutputDetailVo.getNetWeight()));
//                    BigDecimal bigDecimalGood = new BigDecimal(String.valueOf(degreasOutput.getBadOutputWeight()));
//                    String s = bigDecimalOld.add(bigDecimalGood).toString();
//                    degreasOutput.setBadOutputWeight(Double.parseDouble(s));
//                }
//                degreasOutputDetailService.save(degreasOutputDetail);
//            }

            //制令单每产出一个批次后，触发生成一条品质检验单；
            // 生成品质检验单
            Long menuId = feignService.getIdByMenuName("脱脂产出");
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            if (sysDocument.getDocCode() == null) {
                throw new GlobalException("未找到相应的检验项目，请前往“质量管理“---”检验配置”页配置");
            }
            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
            if (documentCheckDtoList.size() < 1) {
                throw new GlobalException("未进行检验单生成配置");
            }
            //通过物料编码获取物料类别
            MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, degreasOutput.getMaterialCode()));

//            for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
//
//                QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
//                qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
//                qualityInspectionDocumentVo.setCategory(Integer.parseInt(materialFinished.getCategory()));
//                qualityInspectionDocumentVo.setMaterialCategory(materialFinished.getMaterialType());
//                qualityInspectionDocumentVo.setMaterialCode(degreasOutput.getMaterialCode());
//                qualityInspectionDocumentVo.setBatchNo(degreasOutputDetail.getBatchNumber());
//                qualityInspectionDocumentVo.setProductionLine(degreasOutput.getLineCode());
//                qualityInspectionDocumentVo.setAssociatedNo(degreasOutput.getDegreasOrderNumber());
//                qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
////                    qualityInspectionDocumentVo.setDifferentString(supplierManagement.getSupplierNum());
//                qualityInspectionDocumentVo.setModeType(20);
//
//                List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
//                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
//                materialNumberAndBatchNoVo.setBatchNo(degreasOutputDetail.getBatchNumber());
//                materialNumberAndBatchNoVo.setMaterialNumber(degreasOutputDetail.getMaterialNumber());
//                materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
//                qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);
//
//                qualityFeginService.addDegreas(qualityInspectionDocumentVo);
//            }
            degreasDocumentService.updateById(degreasDocument);
//            //将脱脂产出中的产出数量+1
//            int outputNumber = degreasOutput.getOutputNumber();
//            degreasOutput.setOutputNumber(outputNumber + 1);
            return updateById(degreasOutput);
        } else {
            throw new GlobalException("只能对状态为“生产中”的制令单进行产出打印");
        }
    }

    /**
     * 扫描入库
     *
     * @param scanInVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ScanInDto scanIn(ScanInVo scanInVo) throws Exception {
        ScanInDto scanInDto = new ScanInDto();

        //获取对应的脱脂明细数据
        DegreasOutputDetail degreasOutputDetail = degreasOutputDetailMapper.selectOne(new QueryWrapper<DegreasOutputDetail>().lambda().eq(DegreasOutputDetail::getMaterialNumber, scanInVo.getInputValue()));
        if (degreasOutputDetail == null) {
            scanInDto.setCode("500");
            scanInDto.setResultMessage("该物料不存在,请核实");
            return scanInDto;
        }
        if (degreasOutputDetail.getStatus() == 2) {
            scanInDto.setCode("500");
            scanInDto.setResultMessage("该物料已入库");
            return scanInDto;
        }
        DegreasDocument degreasDocument = degreasDocumentMapper.selectOne(new QueryWrapper<DegreasDocument>().lambda().eq(DegreasDocument::getDegreasOrderNumber, degreasOutputDetail.getDegreasOrderNumber()));

        //包号
        int i = 1;
        String newNumber = degreasOutputDetail.getCylinderNumber();
        List<DegreasOutputDetail> degreasOutputDetails = degreasOutputDetailMapper.selectList(new QueryWrapper<DegreasOutputDetail>().lambda().eq(DegreasOutputDetail::getDegreasOrderNumber, degreasOutputDetail.getDegreasOrderNumber()).eq(DegreasOutputDetail::getCylinderNumber, newNumber).orderByDesc(DegreasOutputDetail::getOutputTime));

        if (degreasOutputDetails.size() > 0) {
            String cylinderNumber = degreasOutputDetails.get(0).getCylinderNumber();
            if (newNumber.equals(cylinderNumber)) {
                i = degreasOutputDetails.get(0).getPackNumber() + 1;
            }
        }
        //生成品质检验单
//        DegreasOutputDetail degreasOutputDetail = new DegreasOutputDetail();
        DegreasOutput degreasOutput = degreasOutputMapper.selectOne(new QueryWrapper<DegreasOutput>().lambda().eq(DegreasOutput::getDegreasOrderNumber, degreasOutputDetail.getDegreasOrderNumber()));
        String batchNumber = degreasOutputDetail.getBatchNumber();
        String degreasOrderNumber = degreasOutput.getDegreasOrderNumber();
        AjaxResult documentByBatchNumber = qualityFeginService.getDocumentByBatchNumber(batchNumber, degreasOrderNumber);
        //获取该批次下的已完成的品质检验单数据
        QualityInspectionDocumentDto qualityInspectionDocumentDto = JSON.parseObject(JSON.toJSONString(documentByBatchNumber.get("data")), QualityInspectionDocumentDto.class);
        String dc = feignService.splitList("DC");

        String str1 = degreasOrderNumber.substring(0, degreasOrderNumber.indexOf("-"));
        String str2 = degreasOrderNumber.substring(str1.length() + 1);
        //如果没有获取到已完成的品质检验单
//        DegreasOutputDetail degreasOutputDetail1 = new DegreasOutputDetail();
//        if (qualityInspectionDocumentDto.getInspectionSheetNo() == null) {
//
//            degreasOutputDetail.setMaterialNumber("DC" + str2 + "-" + dc)
//                    .setStatus(1)
//                    .setCheckStatus(1)
////                    .setRemark(degreasOutputDetailVo.getRemark())
//                    .setTemplateId(degreasDocument.getDegreasMark())
//                    .setDegreasOrderNumber(degreasOutput.getDegreasOrderNumber())
//                    .setMaterialCode(degreasOutputDetail.getMaterialCode())
//                    .setCylinderNumber(newNumber)
//                    .setPackNumber(i)
//                    .setBatchNumber(batchNumber)
//                    .setGrossWeight(degreasOutputDetail.getGrossWeight())
//                    .setNetWeight(degreasOutputDetail.getNetWeight())
//                    .setOutputTime(new Date())
//                    .setShift(degreasOutputDetail.getShift())
//                    .setOperator(SecurityUtils.getUsername());
////            degreasOutputDetailService.save(degreasOutputDetail);
//        } else {
//            degreasOutputDetail.setMaterialNumber("DC" + str2 + "-" + dc)
//                    .setStatus(1)
//                    .setCheckStatus(2)
//                    .setCheckResult(Integer.parseInt(qualityInspectionDocumentDto.getInspectionResults()))
////                    .setRemark(degreasOutputDetailVo.getRemark())
//                    .setTemplateId(degreasDocument.getDegreasMark())
//                    .setDegreasOrderNumber(degreasOutput.getDegreasOrderNumber())
//                    .setMaterialCode(degreasOutputDetail.getMaterialCode())
//                    .setCylinderNumber(newNumber)
//                    .setPackNumber(i)
//                    .setBatchNumber(batchNumber)
//                    .setGrossWeight(degreasOutputDetail.getGrossWeight())
//                    .setNetWeight(degreasOutputDetail.getNetWeight())
//                    .setOutputTime(new Date())
//                    .setShift(degreasOutputDetail.getShift())
//                    .setOperator(SecurityUtils.getUsername());
//            if ("1".equals(qualityInspectionDocumentDto.getJudgmentGrade())) {
//                //良品
//                degreasOutputDetail.setMaterialLevel(1);
//            } else if ("3".equals(qualityInspectionDocumentDto.getJudgmentGrade())) {
//                //返工
//                degreasOutputDetail.setMaterialLevel(3);
//            } else {
//                //报废
//                degreasOutputDetail.setMaterialLevel(2);
//            }
//            //如果该单据检验结果为合格
//            if ("1".equals(qualityInspectionDocumentDto.getInspectionResults())) {
//                //将该明细净重作为良品产出重量
//                BigDecimal bigDecimalOld = new BigDecimal(String.valueOf(degreasOutputDetail.getNetWeight()));
//                BigDecimal bigDecimalGood = new BigDecimal(String.valueOf(degreasOutput.getGoodOutputWeight()));
//                String s = bigDecimalOld.add(bigDecimalGood).toString();
//                degreasOutput.setGoodOutputWeight(Double.parseDouble(s));
//                degreasDocument.setGoodOutputWeight(Double.parseDouble(s));
//            } else {
//                //将该明细净重作为不良品产出重量
//                BigDecimal bigDecimalOld = new BigDecimal(String.valueOf(degreasOutputDetail.getNetWeight()));
//                BigDecimal bigDecimalGood = new BigDecimal(String.valueOf(degreasOutput.getBadOutputWeight()));
//                String s = bigDecimalOld.add(bigDecimalGood).toString();
//                degreasOutput.setBadOutputWeight(Double.parseDouble(s));
//            }
//        }
//        degreasOutputDetailService.save(degreasOutputDetail1);

        //制令单每产出一个批次后，触发生成一条品质检验单；
        // 生成品质检验单
        Long menuId = feignService.getIdByMenuName("脱脂产出");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        if (sysDocument.getDocCode() == null) {
            throw new GlobalException("未找到相应的检验项目，请前往“质量管理“---”检验配置”页配置");
        }
        List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
        if (documentCheckDtoList.size() < 1) {
            throw new GlobalException("未进行检验单生成配置");
        }
        //通过物料编码获取物料类别
        MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, degreasOutput.getMaterialCode()));

        for (SysDocumentCheckDto checkDto : documentCheckDtoList) {

            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
            qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
            qualityInspectionDocumentVo.setCategory(Integer.parseInt(materialFinished.getCategory()));
            qualityInspectionDocumentVo.setMaterialCategory(materialFinished.getMaterialType());
            qualityInspectionDocumentVo.setMaterialCode(degreasOutput.getMaterialCode());
            qualityInspectionDocumentVo.setBatchNo(degreasOutputDetail.getBatchNumber());
            qualityInspectionDocumentVo.setProductionLine(degreasOutput.getLineCode());
            qualityInspectionDocumentVo.setAssociatedNo(degreasOutput.getDegreasOrderNumber());
            qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
//                    qualityInspectionDocumentVo.setDifferentString(supplierManagement.getSupplierNum());
            qualityInspectionDocumentVo.setModeType(20);

            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
            MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
            materialNumberAndBatchNoVo.setBatchNo(degreasOutputDetail.getBatchNumber());
            materialNumberAndBatchNoVo.setMaterialNumber(degreasOutputDetail.getMaterialNumber());
            materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
            qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

            qualityFeginService.addDegreas(qualityInspectionDocumentVo);
        }

        WipOtherAddVo wipOtherAddVo = new WipOtherAddVo();
        //获取车间建模下绑定的车间
        SysShopModelingDto warehouseing = sysShopModelingMapper.getWarehouseing(degreasOutput.getLineCode());
        Long id = warehouseing.getModelingBindingStorage();

        //车间
        AjaxResult view = storageFegin.view(id);
        WarehouseDto warehouseDto = JSON.parseObject(JSON.toJSONString(view.get("data")), WarehouseDto.class);
        //数据传输到“库存汇总”页面
        WmsStockInfoVo wmsStockInfoVo = new WmsStockInfoVo();
        //物料号码
        wmsStockInfoVo.setWsiMaterialNumber(degreasOutputDetail.getMaterialNumber());
        //类别(1是原料2是辅料3是半成品4是成品)
        wmsStockInfoVo.setWsiCategory("3");
        //物料编码
        wmsStockInfoVo.setWsiMaterialCode(degreasOutputDetail.getMaterialCode());
        //物料数量
        wmsStockInfoVo.setWsiMaterialNum(1);
        //库存状态
        wmsStockInfoVo.setWsiMaterialStatus(2);
        //物料等级
        wmsStockInfoVo.setWsiMaterialGrade(String.valueOf(degreasOutputDetail.getMaterialLevel()));
        //批次号
        wmsStockInfoVo.setWsiMaterialBatch(degreasOutputDetail.getBatchNumber());
        //毛重
        wmsStockInfoVo.setWsiGorssWeight(degreasOutputDetail.getGrossWeight());
        //净重
        wmsStockInfoVo.setWsiNetWeight(degreasOutputDetail.getNetWeight());
        //仓库
        wmsStockInfoVo.setWsiWarehourse(warehouseDto.getWarehouseCode());
//        //客户编码
//        wmsStockInfoVo.setWsiCustomCode(weighingFinishedMaterialProduct.getCustomerCode());
        //关联单号
        wmsStockInfoVo.setWsiConnectNum(degreasOutput.getDegreasOrderNumber());
        //创建人
        wmsStockInfoVo.setCreateUser(SecurityUtils.getUsername());
        //生产日期
        wmsStockInfoVo.setWsiProducedDate(new Date());
        //入库日期
        wmsStockInfoVo.setWsiReveiveTime(new Date());
        //阶别
        wmsStockInfoVo.setWsiProducedStep("1");
        AjaxResult ajaxResultStock = storageFegin.addWmsStock(wmsStockInfoVo);
        String code2 = ajaxResultStock.get("code").toString();
        if ("200".equals(code2)) {
            wipOtherAddVo.setMakingOrderNo(degreasOutputDetail.getDegreasOrderNumber());
            wipOtherAddVo.setMaterialCode(degreasOutputDetail.getMaterialCode());
            wipOtherAddVo.setMaterialCategory(Integer.parseInt(materialFinished.getCategory()));
            wipOtherAddVo.setPlannedWeight(degreasOutput.getPlanWeight());
            wipOtherAddVo.setWarehousTime(new Date());
            wipOtherAddVo.setReceiveType(3);
            wipOtherAddVo.setGenerationMethod(2);
            wipOtherAddVo.setMaterialNumber(degreasOutputDetail.getMaterialNumber());
            wipOtherAddVo.setGrossWeight(degreasOutputDetail.getGrossWeight());
            wipOtherAddVo.setNetWeight(degreasOutputDetail.getNetWeight());
            wipOtherAddVo.setBatchNo(degreasOutputDetail.getBatchNumber());
            //生成完工入库单
            AjaxResult ajaxResult = storageFegin.wipOtherAdd(wipOtherAddVo);
            String code = ajaxResult.get("code").toString();
            if ("200".equals(code)) {
                degreasOutputDetail.setStatus(2);
                if (qualityInspectionDocumentDto == null) {
                    degreasOutputDetail.setCheckStatus(1);
                }else {
                    degreasOutputDetail.setCheckStatus(2);
                }
                degreasOutputDetail.setCreateBy(SecurityUtils.getUsername());
                degreasOutputDetail.setCreateTime(new Date());
                degreasOutputDetailService.updateById(degreasOutputDetail);
                BigDecimal bigDecimalAll = new BigDecimal(0);
                if (degreasOutput.getGoodOutputWeight() != 0) {
                    bigDecimalAll = new BigDecimal(String.valueOf(degreasOutput.getGoodOutputWeight())).add(new BigDecimal(String.valueOf(degreasOutputDetail.getNetWeight())));
                } else {
                    bigDecimalAll = new BigDecimal(String.valueOf(degreasOutputDetail.getNetWeight()));
                }
                degreasOutput.setGoodOutputWeight(Double.parseDouble(bigDecimalAll.toString()));
                //将脱脂产出中的产出数量+1
                int outputNumber = degreasOutput.getOutputNumber();
                degreasOutput.setOutputNumber(outputNumber + 1);
                updateById(degreasOutput);
                //修改脱脂制令单良品产出数量
                degreasDocument.setGoodOutputWeight(Double.parseDouble(bigDecimalAll.toString()));
                degreasDocumentService.updateById(degreasDocument);
                String result = "物料号码:" + degreasOutputDetail.getDegreasOrderNumber() + "," + "净重:" + degreasOutputDetail.getNetWeight() + "," + "物料名称:" + materialFinished.getMaterialName() + "," + "入库成功";
                scanInDto.setResultMessage(result);
                scanInDto.setCode("200");
                return scanInDto;
            } else {
                throw new GlobalException("生成完工入库单失败");
            }
        } else {
            throw new GlobalException("物料入库失败");
        }
    }

    /**
     * 废料打印
     *
     * @param wasteTubeVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WasteTubeVo wastePrint(WasteTubeVo wasteTubeVo) throws Exception {
//        DegreasOutput degreasOutput = getById(wasteTubeVo.getId());
        WasteTube wasteTube = new WasteTube();
        String authorityCoding = feignService.getAuthorityCoding("productionTube:prostatistics:wastemanage:list");
        wasteTube.setWasteScrapNumber(authorityCoding)
                .setFeedOrderNumber(wasteTubeVo.getDegreasOrderNumber())
                .setWasteCode(wasteTubeVo.getWasteCode())
                .setGrossWeight(wasteTubeVo.getGrossWeight())
                .setTareWeight(wasteTubeVo.getTareWeight())
                .setNetWeight(wasteTubeVo.getNetWeight())
                .setLineCode(wasteTubeVo.getLineCode())
                .setPrinterBy(SecurityUtils.getUsername())
                .setPrinterTime(new Date())
                .setWasteType(1);


        int i = wasteTubeMapper.insertWasteTube(wasteTube);

        wasteTubeVo.setLevelProduction("脱脂");
        wasteTubeVo.setWasteScrapNumber(authorityCoding);


        return wasteTubeVo;
    }

    /**
     * 单据完成
     *
     * @param id
     * @return
     */
    @Override
    public boolean documentsFinish(Long id) {
        //只能对状态为“生产中、暂停”的单据进行单据完成操作
        DegreasOutput degreasOutput = getById(id);
        if (degreasOutput.getProductStatus() == 1 || degreasOutput.getProductStatus() == 2) {
            //只有当良品产出重量≥计划重量时，才能操作成功，否则提示“当前制令单没有达到计划重量，无法手动完成”,  完成后单据状态更新为“已完成”
            int round = (int) Math.round(degreasOutput.getGoodOutputWeight());
            int round1 = (int) Math.round(degreasOutput.getPlanWeight());
            if (round >= round1) {
                degreasOutput.setProductStatus(3);
                //同时修改脱脂制令单状态
                DegreasDocument degreasDocument = degreasDocumentMapper.selectOne(new QueryWrapper<DegreasDocument>().lambda().eq(DegreasDocument::getDegreasOrderNumber, degreasOutput.getDegreasOrderNumber()));
                degreasDocument.setStatus(4);
                boolean b = degreasDocumentService.updateById(degreasDocument);
                if (b) {
                    updateById(degreasOutput);
                }
                return b;
            } else {
                throw new GlobalException("当前制令单没有达到计划重量，无法手动完成");
            }
        } else {
            throw new GlobalException("只能对状态为“生产中、暂停”的单据进行单据完成操作");
        }
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public DegreasDocumentDto getView(Long id) {
        DegreasOutput byId = getById(id);
        DegreasDocument degreasDocument = degreasDocumentMapper.selectOne(new QueryWrapper<DegreasDocument>().lambda().eq(DegreasDocument::getDegreasOrderNumber, byId.getDegreasOrderNumber()));
        DegreasDocumentDto dto = degreasDocumentService.queryDegreasDocument(degreasDocument.getId());
        dto.setLevelProduction("脱脂");
        return dto;
    }

    /**
     * 产出统计
     *
     * @param id
     * @return
     */
    @Override
    public List<OutputStatisticsDto> outputStatistics(long id) {
        DegreasOutput degreasOutput = getById(id);
        return degreasOutputMapper.outputStatisticsById(degreasOutput.getDegreasOrderNumber());
    }
}
